package br.com.fiap.goaround.scheduler;

import java.util.Date;
import java.util.logging.Logger;

import org.quartz.JobDetail;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;

public class SchedulerJob {
	
	   private static final Logger log = Logger.getLogger("Configuração do Scheduller", SchedulerJob.class.getName());
	 
	   private static SchedulerJob scheduler = null;  
	   
	    public static SchedulerJob getInstance() {  
	       if (scheduler == null) {  
	    	   scheduler = new SchedulerJob();  
	       }  
	       return scheduler;  
	    }  
	   
	    private SchedulerJob() {  
	    }  
	    
		public void run() throws JobExecutionException {
			log.info("inicio da configuração do job "+ new Date());
	    	try {

	    		long ts = TriggerUtils.getNextGivenSecondDate(null, 15).getTime();
	    		
	    		// First we must get a reference to a scheduler
     	        SchedulerFactory sf = new StdSchedulerFactory();
				Scheduler sched = sf.getScheduler();

		        // define the job and tie it to our HelloJob class
		        JobDetail job = new JobDetail("job1", "group1", UpdateTrafficJob.class);
		       
		        // Trigger the job to run on the next round minute
		        SimpleTrigger trigger =  new SimpleTrigger("trigger1", "group1", new Date(ts), null, SimpleTrigger.REPEAT_INDEFINITELY, 600000L);
		        
		        // Tell quartz to schedule the job using our trigger
		        sched.scheduleJob(job, trigger);

		        // Start up the scheduler (nothing can actually run until the 
		        // scheduler has been started)
		        sched.start();
		        //sched.shutdown(true);
		        log.info("fim da configuração do job");
	    	} catch (SchedulerException e) {
				log.severe(" "+e.getMessage());
			}			
		}
		
		public static void main(String args[]){
			SchedulerJob job = SchedulerJob.getInstance();
			try {
				job.run();
			} catch (JobExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
